package com.zqwm.fly.mongo;

import com.zqwm.fly.types.PageModel;
import com.zqwm.fly.utils.HttpUtils;
import org.json.JSONObject;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by songyifei on 2018-05-22.
 */
@SuppressWarnings("all")
@Repository
public class RecipeMongodb extends Mongodb<Object>
{

    public void getJsonData(String name)
    {
    }


    public static void main(String[] args) throws Exception {
        HttpUtils httpUtils = new HttpUtils();
        String json = httpUtils.get("http://apis.juhe.cn/cook/query.php?menu=%E6%B0%B4%E7%85%AE%E9%B1%BC&dtype=&pn=&rn=&albums=&=&key=5e3c07c1cff0b63d0ba97fa9283c5575");
        //mongoTemplate.save(json);
        System.out.println(json);
    }

    @Override
    public PageModel<Object> findByPage(PageModel<Object> page, Integer pageIndex, Integer pageSize, Map<String, Object> params, String cellection)
    {
        //创建排序模板Sort
        Sort sort = new Sort(Sort.Direction.DESC, "id");

        //创建分页模板Pageable
        Pageable pageable = new PageRequest(pageIndex-1, pageSize, sort);

        //创建查询条件对象
        Query query = new Query();
        if ((params != null) && (!(params.isEmpty())))
        {
            for (String key : params.keySet())
            {
                if("tags".equals(key))
                {
                    List<String>tags = (List<String>) params.get(key);
                    Criteria[] criteria =new Criteria[tags.size()];
                    for (int i=0;i<tags.size();i++)
                    {
                        criteria[i] = Criteria.where(key).regex(".*?\\" +tags.get(i)+ ".*");
                    }

                    //and/or
                    query.addCriteria(new Criteria().orOperator(criteria));

                }else {
                    //精确查询
                    //query.addCriteria(Criteria.where(key).is(params.get(key)));
                    //模糊查询
                    query.addCriteria(Criteria.where(key).regex(".*?\\" +params.get(key).toString()+ ".*"));
                    //如果是tags
                }
            }
        }

        //mongoTemplate.count计算总数
        long total = mongoTemplate.count(query,getClz(),cellection);
        page.setRowCount((int)total);

        List<Object> items = (List<Object>) mongoTemplate.find(query.with(pageable),getClz(),cellection);

        page.setPageNo(pageIndex);
        page.setPageSize(pageSize);
        page.setDatas(items);

        return page;
    }

}
